//
//  NetworkPath.m
//  freeRide
//
//  Created by HuangSui on 2017/4/4.
//  Copyright © 2017年 SuiXun. All rights reserved.
//

#import "NetworkPath.h"

@implementation NetworkPath

//__block
//__weak typeof(self) weakSelf = self;
//__strong typeof(self) strongSelf = weakSelf;



//导航左边按钮
+(UIButton *)SetNavLeftBtnWithController:(UIViewController *)vc withTitle:(NSString *)Btntext andImageName:(NSString *)imageName
{
    //导航栏左边按钮
    UIButton *leftButton = [[UIButton alloc] init];
    leftButton.titleLabel.font=[UIFont systemFontOfSize:16];
    if (Btntext!=nil) {
        [leftButton setTitle:Btntext forState:UIControlStateNormal];
    }
    
    if (imageName!=nil) {
        [leftButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        [leftButton setImage:[UIImage imageNamed:@"返回白"] forState:UIControlStateSelected];
        leftButton.imageEdgeInsets=UIEdgeInsetsMake(0,0,0,22);
    }
    //控件大小适应文字或图片的大小
//    [leftButton sizeToFit];
    leftButton.bounds = CGRectMake(0, 0, 44, 44);
    [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    vc.navigationItem.leftBarButtonItem = leftBtn;
    return leftButton;
}
//导航右边按钮
+(UIButton *)SetNavRightBtnWithController:(UIViewController *)vc withTitle:(NSString *)Btntext andImageName:(NSString *)imageName
{
    //导航栏右边按钮
    UIButton *rightButton = [[UIButton alloc] init];
    rightButton.titleLabel.font=[UIFont systemFontOfSize:16];
    if (Btntext!=nil) {
        [rightButton setTitle:Btntext forState:UIControlStateNormal];
    }
    
    if (imageName!=nil) {
        [rightButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    //控件大小适应文字或图片的大小
    [rightButton sizeToFit];
    [rightButton setTitleColor:[UIColor colorQ] forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    vc.navigationItem.rightBarButtonItem = rightBtn;
    return rightButton;
}

#pragma mark 颜色转换为图片

+ (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
#pragma mark 检测数据类型，替换空数据
+ (id)replaceNullData:(id)obj
{
    
    
    
    if ([obj isKindOfClass:[NSDictionary class]])
    {
        
        return [self replaceNullWithDictionary:obj];
    }
    else if ([obj isKindOfClass:[NSArray class]])
    {
        return [self replaceNullWithArray:obj];
    }
    else if ([obj isKindOfClass:[NSNumber class]])
    {
        if ([obj isKindOfClass:[NSNull class]] || obj == nil) {
            obj = @(0);
        }
        return obj;
    }
    else if ([obj isKindOfClass:[NSString class]]) {
        return [self replaceNullValue:obj];
    }
    else
    {
        NSString *str=[NSString stringWithFormat:@"%@",obj];
        return [self replaceNullValue:str];
    }
    //走不到这里应该
    return obj;
}

#pragma mark--处理字典
+ (id)replaceNullWithDictionary:(NSMutableDictionary *)dic
{
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    NSArray *allKey = [dic allKeys];
    for (NSString *key in allKey) {
        
        [tempDic setObject:[self replaceNullData:dic[key]] forKey:key];
    }
    return tempDic;
}

#pragma mark--处理数组
+ (id)replaceNullWithArray:(NSMutableArray *)arr
{
    __block NSMutableArray *tempArr = [NSMutableArray array];
    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
     {
         [tempArr addObject:[self replaceNullData:obj]];
     }];
    return tempArr;
}

#pragma mark --处理字符串
+ (NSString *)replaceNullValue: (NSString *)string
{
    NSString * newStr = [NSString stringWithFormat:@"%@",string];
    //Nil ||NULL
    if ([newStr isKindOfClass:[NSNull class]] ||
        newStr == nil ||
        [newStr isEqualToString:@"(null)"]||
        [newStr isEqualToString:@""] ||
        [newStr isEqualToString:@"null"] ||
        [newStr isEqualToString:@"<null>"])
    {
        
        newStr = @"";
    }
    return newStr;
}



//kvc 获取所有key值
- (NSArray *)getAllIvar:(id)object
{
    NSMutableArray *array = [NSMutableArray array];
    
    unsigned int count;
    Ivar *ivars = class_copyIvarList([object class], &count);
    for (int i = 0; i < count; i++) {
        Ivar ivar = ivars[i];
        const char *keyChar = ivar_getName(ivar);
        NSString *keyStr = [NSString stringWithCString:keyChar encoding:NSUTF8StringEncoding];
        @try {
            id valueStr = [object valueForKey:keyStr];
            NSDictionary *dic = nil;
            if (valueStr) {
                dic = @{keyStr : valueStr};
            } else {
                dic = @{keyStr : @"值为nil"};
            }
            [array addObject:dic];
        }
        @catch (NSException *exception) {}
    }
    return [array copy];
}

//获得所有属性
- (NSArray *)getAllProperty:(id)object
{
    NSMutableArray *array = [NSMutableArray array];
    
    unsigned int count;
    objc_property_t *propertys = class_copyPropertyList([object class], &count);
    for (int i = 0; i < count; i++) {
        objc_property_t property = propertys[i];
        const char *nameChar = property_getName(property);
        NSString *nameStr = [NSString stringWithCString:nameChar encoding:NSUTF8StringEncoding];
        [array addObject:nameStr];
    }
    return [array copy];
}
+(void)leaveVC
{
    
    
//    [JPUSHService setTags:nil alias:@"" fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
//
//        if (iResCode!=0) {
//
//            LRLog(@"极光设置别名失败");
//        }
//    }];
//    EMError *error = [[EMClient sharedClient] logout:YES];
//    if (!error) {
//        NSLog(@"退出成功");
//    }
    
    //清除token
    
    [UDF removeObjectForKey:@"token"];
    [UDF removeObjectForKey:@"cookie"];
    
    [UDF synchronize];
    
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    [appDelegate switchController];
}
+(void)DownloadTask
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", filePath);
    }];
    [downloadTask resume];
}
+(void)UploadTask
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"Success: %@ %@", response, responseObject);
        }
    }];
    [uploadTask resume];
}
+(void)MultiPartRequest:(NSString *)URLString andParameters:(NSDictionary*)parameters andValueFilePathWithKeyFileName:(NSDictionary *)fileDic RequestSuccess:(RequestSuccess)requestSuccess RequestFailed:(RequestFailed)requestFailed
{
    
    
    //file,filename.jpg,image/jpeg,POST写死了
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        
        
        NSArray *dictKeysArray = [fileDic allKeys];
        for (int i = 0; i<dictKeysArray.count; i++) {
            
            NSString *filename = dictKeysArray[i];
            NSString *path =[fileDic objectForKey:filename];
            NSString *Netname;
            Netname = [NSString stringWithFormat:@"file[%d]",i];

        [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
        }
    } error:nil];
    if (![NSString isNULLString:COOKIE])
    {
        [request setValue:COOKIE forHTTPHeaderField:@"X-Auth-Token"];
    }
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                      dispatch_async(dispatch_get_main_queue(), ^{
//    [progressView setProgress:uploadProgress.fractionCompleted];
                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          requestFailed (error);
                      } else {
                          NSHTTPURLResponse *myresponse = (NSHTTPURLResponse *)response;
                          NSDictionary *allHeaders = myresponse.allHeaderFields;
                          
                          if (allHeaders[@"X-Auth-Token"]) {
                              NSString *str=[NSString stringWithFormat:@"%@",allHeaders[@"X-Auth-Token"]];
                              [UDF setObject:str forKey:@"cookie"];
                              
                          }
                          requestSuccess(response ,responseObject);
                      }
                  }];
    
    [uploadTask resume];
}

+(void)requestWithMethod:(TTGState)type andURLString:(NSString *)URL andParameters:(NSDictionary*)parameters RequestSuccess:(RequestSuccess)requestSuccess RequestFailed:(RequestFailed)requestFailed
{
    
    

    
    NSString *URLString = [NSString stringWithFormat:@"%@%@",APPBaseUrl,URL];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    
    
    
    //https
    AFHTTPSessionManager *smanager = [AFHTTPSessionManager manager];
    // not recommended for production
    smanager.securityPolicy.allowInvalidCertificates = YES;
    
    
    NSMutableURLRequest *request;
    switch (type) {
        case 0:
            //原始数据
            request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
            break;
        case 1:
            //原始数据
            request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
            break;
        case 2:
            //参数序列化
            request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
            break;
            
        default:
            break;
    }
    if (![NSString isNULLString:COOKIE])
    {
        [request setValue:COOKIE forHTTPHeaderField:@"X-Auth-Token"];
    }
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            requestFailed (error);
        } else {
            
            NSHTTPURLResponse *myresponse = (NSHTTPURLResponse *)response;
            NSDictionary *allHeaders = myresponse.allHeaderFields;
            
            if (allHeaders[@"X-Auth-Token"]) {
                NSString *str=[NSString stringWithFormat:@"%@",allHeaders[@"X-Auth-Token"]];
                [UDF setObject:str forKey:@"cookie"];
                
            }
            
            
            
            
            requestSuccess(response ,responseObject);
        }
    }];
    [dataTask resume];
    
    
    
    
    //示例
    /*
     NSString *URLString = @"/axq/admin/users";
     NSDictionary *parameters = @{@"peopletel": @""};
     [NetworkPath requestWithMethod:0 andURLString:URLString andParameters:parameters RequestSuccess:^(NSURLResponse *response, id responseObject) {
     NSLog(@"%@",responseObject);
     NSString *code=[NetworkPath getValue:@"code" from:responseObject];
     if (code.length) {
     if([code isEqualToString:@"10008"])
     {
     
     }else
     {
     NSString *str=[NetworkPath getValue:@"msg" from:responseObject];
     
     [self.view makeToast:str];
     }
     }
     
     } RequestFailed:^(NSError *error) {
     
     }];
    */
    
//    /axq/admin/{uid} （没有用到这个接口）
//    /axq/admin/users（参数查询没有用）
    
}
+(NSString *)getValue:(NSString *)key from:(id)object
{
    //1.先判断responseObject是不是字典
    if ([object isKindOfClass:[NSDictionary class]]) {
        //2.再判断字典有没有code key
        
        if (object[key]) {
            //3. code转化为字符串 防止类型崩溃
            NSString *code = [NSString stringWithFormat:@"%@",object[key]];
            return code;
        }
    }
    return @"";
}
+(BOOL)isDictionary:(NSString *)key from:(id)object
{
    if ([object isKindOfClass:[NSDictionary class]])
    {
        if (object[key]) {
            if ([object[key] isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic=object[key];
                                if (dic.count) {
                
                                    return YES;
                                }
            }
        }
    }
    
    return NO;
}
+(BOOL)isNSArray:(NSString *)key from:(id)object
{
    if ([object isKindOfClass:[NSDictionary class]])
    {
        if (object[key])
        {
            if ([object[key] isKindOfClass:[NSArray class]]) {
                NSArray *arr=object[key];
                             if (arr.count) {
                                 return YES;
                             }
            }
        }
    }
    return NO;
}
+(NSDictionary *)GetDictionary:(NSString *)key from:(id)object
{
    if ([object isKindOfClass:[NSDictionary class]])
    {
        if (object[key]) {
            if ([object[key] isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic=object[key];
                if (dic.count) {

                    return dic;
                }
            }
        }
    }
    
    return [NSDictionary dictionary];
}
+(NSArray *)GetNSArray:(NSString *)key from:(id)object
{
  if ([object isKindOfClass:[NSDictionary class]])
  {
     if (object[key])
     {
         if ([object[key] isKindOfClass:[NSArray class]]) {
             NSArray *arr=object[key];
             if (arr.count) {
                 return arr;
             }
         }
     }
  }
    return [NSArray array];
}
//loc  表示将str1插入str0哪个位置
+(NSMutableAttributedString *)setRichText:(NSString *)str0 withFont:(CGFloat) size0 withColor:(UIColor *)color0 andOtherText:(NSString *)str1 withFont:(CGFloat) size1 withColor:(UIColor *)color1 atIndex:(NSUInteger)loc
{
    NSMutableString *sumStr=[[NSMutableString alloc]initWithString:str0];
    [sumStr insertString:str1 atIndex:loc];
    NSMutableAttributedString *richText = [[NSMutableAttributedString alloc] initWithString:sumStr];
    [richText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:size0] range:NSMakeRange(0, sumStr.length)];
    [richText addAttribute:NSForegroundColorAttributeName value:color0 range:NSMakeRange(0, sumStr.length)];
    [richText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:size1] range:NSMakeRange(loc, str1.length)];
    [richText addAttribute:NSForegroundColorAttributeName value:color1 range:NSMakeRange(loc, str1.length)];
    return richText;
    
}
-(void)testFction
{
//    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
//                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
//    
//    
//    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
//                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]
//                             completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//                                 ... completion code here ...
//                             }];
//    
//    
//    
//    SDWebImageManager *manager = [SDWebImageManager sharedManager];
//    [manager loadImageWithURL:imageURL
//                      options:0
//                     progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//                         // progression tracking code
//                     }
//                    completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//                        if (image) {
//                            // do something with image
//                        }
//                    }];
}




@end
